const jwt = require("jsonwebtoken");

const secret = "123456";

// 生成 token
const getToken = (payload) => {
  const token = jwt.sign(payload, secret, { expiresIn: "5s" });
  console.log("token 生成成功", payload);
  return token;
};

// 生成短 token
const getShortToken = (payload) => {
  const shortToken = jwt.sign(payload, secret, { expiresIn: "5s" });
  console.log("短 token 生成成功", payload);
  return shortToken;
};

// 生成长 token
const getLongToken = (payload) => {
  const longToken = jwt.sign(payload, secret, { expiresIn: "15s" });
  console.log("长 token 生成成功", payload);
  return longToken;
};

// 测试用的鉴权中间价
const authMiddleware = async (ctx, next) => {
  const token = ctx.headers.authorization; // 从 Authorization 头获取 token

  console.log("token 被获取", token);

  // 如果没有 token 则返回 401
  if (!token) {
    ctx.status = 401;
    ctx.body = {
      code: 401,
      message: "Token is required",
    };

    return;
  }

  try {
    const decoded = jwt.verify(token, secret);

    // 将解码后的用户信息存入 ctx.state 中
    ctx.state.user = decoded;
    ctx.req.user = decoded;

    console.log("token 被正常的解析了");

    return next();
  } catch (error) {
    ctx.status = 401;
    ctx.body = {
      code: 401,
      message: "Token is invalid",
    };

    return;
  }
};

// 验证 token 的中间件
const verifyToken = async (ctx, next) => {
  const token = ctx.headers.authorization; // 从 Authorization 头获取 token
  if (!token) {
    ctx.status = 401;
    ctx.body = {
      code: 401,
      message: "Token is required",
    };
    return;
  }

  try {
    const decoded = jwt.verify(token, secret);
    // 将解码后的用户信息存入 ctx.state 中
    ctx.state.user = decoded;
    ctx.req.user = decoded;

    console.log("token 被正常的解析了");

    return next();
  } catch (error) {
    if (error.name === "TokenExpiredError") {
      // 从过期的 token 中解码用户信息
      const decoded = jwt.decode(token);
      if (decoded) {
        // 生成新的 token
        console.log("token 已过期 但 token 有效", decoded);
        const newToken = getToken({ email: decoded.email });
        ctx.set("Authorization", newToken); // 将新 token 添加到响应头
        ctx.status = 451;
        ctx.body = {
          code: 451,
          message: "newToken has",
          // newToken: newToken, // 也可以在响应体中返回新 token
        };

        // 将解码后的用户信息存入 ctx.state 和 ctx.req 中
        ctx.state.user = decoded;
        ctx.req.user = decoded;
      } else {
        ctx.status = 401;
        ctx.body = {
          code: 401,
          message: "Token is invalid",
        };

        console.log("token 已过期 但 token 无效");
      }
      return;
    }

    ctx.status = 401;
    ctx.body = {
      code: 401,
      message: "Token is invalid",
    };
    return;
  }
};

// 解码 token
const decodeToken = (token) => {
  return jwt.decode(token);
};

module.exports = {
  getToken,
  verifyToken,
  getShortToken,
  getLongToken,
  authMiddleware,
};
